package com.physics.mps.module.util;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.physics.mps.common.config.properties.ApiProperties;
import com.physics.mps.common.exception.BusinessException;
import com.physics.mps.common.util.AssertUtil;
import com.physics.mps.common.util.OkHttpUtil;
import com.physics.mps.entity.enums.CodeEnum;
import com.physics.mps.entity.vo.api.Result;
import com.physics.mps.entity.vo.api.UploadVo;
import lombok.RequiredArgsConstructor;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mcsoft
 * @since 2023/11/30
 */
@Component
@RequiredArgsConstructor
public class UploadDownloadFile {
    @Autowired
    private static ApiProperties apiProperties;

    /**
     * 上传结果文件
     * @param local
     * @return
     */
    public static String uploadResultFile(String local) {
        Map<String, String> params = new HashMap<>(8);
        File file = new File(local) ;

        Map<String, String> urls = apiProperties.getUrls();
        String url = urls.get("upload-file");
        params.put("moduleName", apiProperties.getModuleName());
        params.put("accessKey", apiProperties.getAccessKey());
        params.put("secretKey", apiProperties.getSecretKey());

        try(Response response = OkHttpUtil.uploadFile(url, file, params);
            ResponseBody responseBody = response.body()){
            AssertUtil.isNull(responseBody, CodeEnum.UPLOAD_EXCEPTION);
            String body = new String(responseBody.bytes());
            Result<UploadVo> result = JSONUtil.toBean(body, new TypeReference<Result<UploadVo>>() {}, false);
            AssertUtil.isFalse(CodeEnum.UPLOAD_EXCEPTION, result.getCode() == 200);
            UploadVo resultData = result.getData();
            return resultData.getUrl();
        }catch (Exception e){
            throw new BusinessException(e.getMessage());
        }
    }
}
